//
//  PopComponent.m
//  分享demo
//
//  Created by pc-chtypd056 on 2018/8/21.
//  Copyright © 2018年 CTL. All rights reserved.
//

#import "PopComponent.h"

@interface CTLAction()

@end

@implementation CTLAction

+ (instancetype)actionWithTitle:(NSString *)title style:(CTLActionStyle)style handlerComplete:(void (^)(CTLAction *))handleComplete{
    return [[[self class]alloc]initWithTitle:title style:style handlerComplete:handleComplete];
}

- (instancetype)initWithTitle:(NSString *)title style:(CTLActionStyle)style handlerComplete:(void (^)(CTLAction *))handleComplete{
    if (self = [super init]) {
        self.style = style;
        self.title = title;
        self.aHandleComplete = handleComplete;
    }
    return self;
}

@end

@interface PopComponent()

@property (nonatomic, strong) UIView *backgroundView;

@property (nonatomic, strong) NSMutableArray *actionArray;
/** 底部button */
@property (nonatomic, strong) UIButton *bottomBtn;
/**title */
@property (nonatomic, strong) UILabel *titleLabel;
/** message */
@property (nonatomic, strong) UILabel *messageLabel;

@end

@implementation PopComponent

+ (instancetype)popComponentWihtTitle:(NSString *)title message:(NSString *)message style:(CTLPopComponentStyle)style{
    return [[[self class]alloc]initWithpopComponentWihtTitle:title message:message style:style];
}

- (instancetype)initWithpopComponentWihtTitle:(NSString *)title message:(NSString *)message style:(CTLPopComponentStyle)style{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        self.title = title;
        self.message = message;
        self.style = style;
        [self setUpSubViews];
    }
    return self;
}

- (void)setUpSubViews{
    
    self.backgroundView = [[UIView alloc]init];
    self.backgroundView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.backgroundView];
    
    if (self.style == CTLPopComponentStyleActionAlert) {
        self.backgroundView.frame = CGRectMake(0, 0, ScreenWIDTH-100, 250);
        self.backgroundView.layer.cornerRadius = 10;
        self.backgroundView.layer.masksToBounds = YES;
        
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    @weakify(self);
    if (self.style == CTLPopComponentStyleActionSheet) {
        
        self.backgroundView.backgroundColor = [UIColor clearColor];
        
        UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.backgroundView.width, 250)];
        contentView.backgroundColor = [UIColor whiteColor];
        [self.backgroundView addSubview:contentView];
        
        UIView *buttomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.backgroundView.y-70, self.backgroundView.width, 60)];
        buttomView.backgroundColor = contentView.backgroundColor;
        [self.backgroundView addSubview:buttomView];
        
        contentView.layer.cornerRadius = 10;
        contentView.layer.masksToBounds = YES;
        
        buttomView.layer.cornerRadius = 10;
        buttomView.layer.masksToBounds = YES;
        
        CGSize titleSize = [self.title sizeWithFont:[UIFont systemFontOfSize:15] maxsize:CGSizeMake(self.backgroundView.width, self.backgroundView.height)];
        self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 11, self.backgroundView.width, titleSize.height+15)];
        self.titleLabel.text = self.title;
        self.titleLabel.textColor = Color_RGB(160, 160, 160);
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.backgroundView addSubview:self.titleLabel];
        
        CGSize messageSize = [self.message sizeWithFont:[UIFont systemFontOfSize:15] maxsize:CGSizeMake(self.backgroundView.width-20, self.backgroundView.height)];
        self.messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, self.titleLabel.height+self.titleLabel.y, self.backgroundView.width-20, messageSize.height+10)];
        self.messageLabel.text = self.message;
        self.messageLabel.textColor = Color_RGB(160, 160, 160);
        self.messageLabel.textAlignment = NSTextAlignmentCenter;
        self.messageLabel.numberOfLines = 0;
        self.messageLabel.font = [UIFont systemFontOfSize:15];
        [self.backgroundView addSubview:self.messageLabel];
        
        CTL_WS
        NSMutableArray *newArray = [NSMutableArray  array];
        [self.actionArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[CTLAction class]]) {
                CTLAction *action = (CTLAction*)obj;
                if (action.style == CTLActionStyleCancel) {
                    [ws.actionArray removeObject:action.title];
                    ws.bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    [ws.bottomBtn setTitle:action.title forState:UIControlStateNormal];
                    [ws.bottomBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    ws.bottomBtn.frame = CGRectMake(0, 0, ws.backgroundView.width, 60);
                    [buttomView addSubview:ws.bottomBtn];
                    [[ws.bottomBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
                        @strongify(self);
                        [self dismissWithCompletion:^{
                            if (action.aHandleComplete) {
                                action.aHandleComplete(action);
                            }
                        }];
                    }];
                    
                }else{
                    if (idx == 0) {
                        ws.bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                        [ws.bottomBtn setTitle:action.title forState:UIControlStateNormal];
                        [ws.bottomBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                        ws.bottomBtn.frame = CGRectMake(0, 0, ws.backgroundView.width, 60);
                        [buttomView addSubview:ws.bottomBtn];
                        [[ws.bottomBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
                            @strongify(self);
                            [self dismissWithCompletion:^{
                                if (action.aHandleComplete) {
                                    action.aHandleComplete(action);
                                }
                            }];
                        }];
                    }
                    
                    if (idx != 0) {
                        [newArray addObject:action];
                    }
                    
                }
            }
        }];
        
        [newArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[CTLAction class]]) {
                CTLAction *action = (CTLAction *)obj;
                ws.bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                [ws.bottomBtn setTitle:action.title forState:UIControlStateNormal];
                [ws.bottomBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                ws.bottomBtn.frame = CGRectMake(0, (idx*60)+ws.messageLabel.height+ws.titleLabel.height+30, ws.backgroundView.width, 60);
                [contentView addSubview:ws.bottomBtn];
                [[ws.bottomBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
                    @strongify(self);
                    
                    [self dismissWithCompletion:^{
                        if (action.aHandleComplete) {
                            action.aHandleComplete(action);
                        }
                    }];
                    
                }];
                
                
                if (idx == 0) {
                    [ws.bottomBtn addLineWithFrame:CGRectMake(0, 0, ws.bottomBtn.width, 1) color:SepeLineColor];
                }
                [ws.bottomBtn addLineWithFrame:CGRectMake(0, ws.bottomBtn.height, ws.bottomBtn.width, 1) color:SepeLineColor];
            }
        }];
        
        contentView.height = self.titleLabel.height+self.messageLabel.height+self.bottomBtn.height*self.actionArray.count+30-60;
        buttomView.frame = CGRectMake(0, contentView.height+10, self.backgroundView.width, 60);
        self.backgroundView.height = contentView.height+buttomView.height;
        self.backgroundView.y = ScreenHEIGH- self.backgroundView.height-20;
        
    }else if (self.style == CTLPopComponentStyleActionAlert){
        
        CGSize titleSize = [self.title sizeWithFont:[UIFont systemFontOfSize:20] maxsize:CGSizeMake(self.backgroundView.width, self.backgroundView.height)];
        self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 25, self.backgroundView.width, titleSize.height+15)];
        self.titleLabel.text = self.title;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
        [self.backgroundView addSubview:self.titleLabel];
        
        CGSize messageSize = [self.message sizeWithFont:[UIFont systemFontOfSize:17] maxsize:CGSizeMake(self.backgroundView.width-20, self.backgroundView.height)];
        self.messageLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, self.titleLabel.height+self.titleLabel.y, self.backgroundView.width-20, messageSize.height+10)];
        self.messageLabel.text = self.message;
        self.messageLabel.textAlignment = NSTextAlignmentCenter;
        self.messageLabel.numberOfLines = 0;
        [self.backgroundView addSubview:self.messageLabel];
        @strongify(self);
        [self.actionArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[CTLAction class]]) {
                CTLAction *action = (CTLAction *)obj;
                self.bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                self.bottomBtn.frame = CGRectMake(idx*self.backgroundView.width/2, self.messageLabel.height+self.messageLabel.y+15, self.backgroundView.width/2, 50);
                [self.bottomBtn setTitle:action.title forState:UIControlStateNormal];
                [self.bottomBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [self.backgroundView addSubview:self.bottomBtn];
                [[self.bottomBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
                    
                    if (idx < self.actionArray.count) {
                        CTLAction *action = self.actionArray[idx];
                        [self dismissWithCompletion:^{
                            if (action.aHandleComplete) {
                                action.aHandleComplete(action);
                            }
                        }];
                    }
                }];
                
                if (idx == 0) {
                    [self.backgroundView addLineWithFrame:CGRectMake(0, self.bottomBtn.y, self.backgroundView.width, 1) color:SepeLineColor];
                    [self.bottomBtn addLineWithFrame:CGRectMake(self.bottomBtn.width, 0, 1, self.bottomBtn.height) color:SepeLineColor];
                }
                
            }
        }];
        self.backgroundView.height = self.titleLabel.height+self.messageLabel.height+self.bottomBtn.height+40;
    }
}

- (void)willMoveToWindow:(UIWindow *)newWindow{
    [super willMoveToWindow:newWindow];
    if (self.style == CTLPopComponentStyleActionSheet) {
       self.backgroundView.frame = CGRectMake(25, ScreenHEIGH-self.backgroundView.height, ScreenWIDTH-50, self.backgroundView.height);
    }else if (self.style == CTLPopComponentStyleActionAlert){
        self.backgroundView.center = self.center;
    }
}

#pragma mark - PopComponentDelegate
- (void)show{
    
    [self showWithCompletion:nil];
}


- (void)showWithCompletion:(dispatch_block_t)complete{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (!window) {
        window = [UIApplication sharedApplication].windows[0];
    }
    [window addSubview:self];
    
    CTL_WS
    if (self.style == CTLPopComponentStyleActionSheet) {
        [UIView animateWithDuration:0.25 animations:^{
            ws.backgroundView.frame = CGRectMake(25, 0, ScreenWIDTH-50, ws.backgroundView.height);
            
        } completion:^(BOOL finished) {
            
            if (complete) {
                complete();
            }
        }];
    }else if (self.style == CTLPopComponentStyleActionAlert){
        [self.backgroundView.layer scale];
        if (complete) {
            complete();
        }
    }
    
    
}

- (void)dismiss{
    
    [self dismissWithCompletion:nil];
}

- (void)dismissWithCompletion:(dispatch_block_t)complete{
    CTL_WS
    if (self.style == CTLPopComponentStyleActionAlert) {
        [UIView animateWithDuration:0.25 animations:^{
            
        } completion:^(BOOL finished) {
            [ws removeFromSuperview];
            if (complete) {
                complete();
            }
        }];
    }else if (self.style == CTLPopComponentStyleActionSheet){
        [UIView animateWithDuration:0.25 animations:^{
            ws.backgroundView.frame = CGRectMake(25, ScreenHEIGH, ScreenWIDTH-50, ws.backgroundView.height);
        } completion:^(BOOL finished) {
            [ws removeFromSuperview];
            if (complete) {
                complete();
            }
        }];
    }
}

- (void)addAction:(CTLAction *)action{
    
    if (action) {
        [self.actionArray addObject:action];
        
    }
}


#pragma mark - lazzy
- (NSMutableArray *)actionArray{
    if (!_actionArray) {
        _actionArray = [NSMutableArray array];
    }
    return _actionArray;
}

@end
